// 文件上传
var errinfo = require('../errinfo.js');
var responseJsonUtils = require('../utils/responseJsonUtils.js');
var formParser = require('../utils/formParser')();
var qiniuUtil = require('../utils/qiniuUtil');

var uploadImage = qiniuUtil.uploadImage;

var upload = module.exports = {};
/**
 * upload file to qiniu
 */
// file not exist
upload.checkInput = function (req, res, next) {

    // if (typeof req.body.id === 'undefined') {
    //     next(responseJsonUtils.json(errinfo.uploadIdEmpty, 403));
    //     return;
    // }

    // if (typeof req.body.kind === 'undefined') {
    //     next(responseJsonUtils.json(errinfo.uploadKindEmpty, 403));
    //     return;
    // }
    if (typeof req.body.file === 'undefined') {
        next(responseJsonUtils.json(errinfo.uploadFileEmpty, 403));
        return;
    }
    next();
};
// form parser
upload.formParser = formParser;
// upload image
upload.uploadFile = function (req, res, next) {

    var body = req.body;

    uploadImage(req.body.file.binaryBuff, req.body.file.ext, function (err, url) {
        if (err) {
            next(responseJsonUtils.json(err, 403));
            return;
        }

        // body.file.url = url;
        // body.file.url = qiniuUtil.getDownloadUrl(url);
        body.file.url = url;
        next();
    });
};

upload.storeRecord = function (req, res, next) {

    UploadRecord.create({
            name: req.body.file.name,
            mime: req.body.file.mime, // mime
            ext: req.body.file.ext, //文件后缀,
            hash: req.body.file.hash, // 文件 hash
            size: req.body.file.size, // 文件大小
            url: req.body.file.url,
            user: req.session.user, // 操作用户
            related: {
                kind: req.body.kind,
                item: req.body.id
            }
        },
        function (err, uploadRecordResult) {
            if (err) {
                next(responseJsonUtils.json(errinfo.mongodb.internalError));
                return;
            }
            res.status(200).json(uploadRecordResult.toJSON());
        }
    );

};


